const parser = require("../parser/index");
function Subtitle(subtitle, type) {
  if (typeof subtitle === "string") {
    this.subtitle = parser.parse(subtitle);
    if (type !== "SRT" || type !== "LRC") {
      this.type = parser.type(subtitle);
    } else {
      this.type = type;
    }
  } else if (typeof subtitle === "object") {
    this.subtitle = subtitle;
    if (Array.isArray(subtitle)) {
      // SRT
      this.type = "SRT";
    } else {
      // LRC
      this.type = "LRC";
    }
  } else if (typeof subtitle === "undefined") {
    return {parse: parser.parse};
  } else {
    throw Error("Not supported type");
  }

  this.getNowSubtitle = function () {
    let seconds = 0;
    if (arguments.length === 4) {
      // hour, minute, second, miillisecond
      seconds = (arguments[0] * 3600) + (arguments[1] * 60) + arguments[2] + (arguments[3] / 1000);
    } else if (arguments.length === 3) {
      // minute, second, millisecond
      seconds = (arguments[0] * 60) + arguments[1] + (arguments[2] / 1000);
    } else if (arguments.length === 1) {
      // seconds
      seconds = arguments[0];
    } else {
      throw Error("Bad parameter");
    }
    if (this.type === "SRT") {
      return getNowSRTSubtitle(this.subtitle, seconds);
    } else if (this.type === "LRC") {
      return getNowLRCSubtitle(this.subtitle, seconds);
    } else {
      throw Error("Unknown error");
    }
  }
}

function getNowSRTSubtitle(subtitle, time) {
  for (let i = 0;i < subtitle.length;i++) {
    if (time >= subtitle[i].startTime.htmlCurrentTime && time <= subtitle[i].endTime.htmlCurrentTime) {
      return subtitle[i].content;
    }
  }
  return "";
}

function getNowLRCSubtitle(subtitle, time) {
  let offset = (subtitle.offset / 1000) || 0;
  for (let i = 0;i < subtitle.content.length;i++) {
    if (i === subtitle.content.length - 1) {
      if ((time + offset) >= subtitle.content[i].time.htmlCurrentTime) {
        return subtitle.content[i].content;
      }
      return "";
    }
    if ((time + offset) >= subtitle.content[i].time.htmlCurrentTime && (time + offset) < subtitle.content[i + 1].time.htmlCurrentTime) {
      return subtitle.content[i].content;
    }
  }
  return "";
}

module.exports = Subtitle;